import React, { useState, useEffect } from 'react';
import { useEditorStore } from '../store/useEditorStore';
import { 
  getFileHistory, 
  clearFileHistory, 
  deleteFileHistory, 
  formatFileSize, 
  formatTime
} from '../utils/file';
import { FileHistory } from '../types';
import { 
  Upload, 
  Download, 
  Trash2, 
  FolderOpen, 
  FileText, 
  Calendar, 
  HardDrive,
  Search,
  Filter,
  RefreshCw
} from 'lucide-react';
import { toast } from 'sonner';

const Files: React.FC = () => {
  const [fileHistory, setFileHistory] = useState<FileHistory[]>([]);
  const [searchTerm, setSearchTerm] = useState('');
  const [sortBy, setSortBy] = useState<'name' | 'size' | 'lastModified'>('lastModified');
  const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
  const { loadFile } = useEditorStore();

  // 加载文件历史
  const loadFileHistory = () => {
    const history = getFileHistory();
    setFileHistory(history);
  };

  useEffect(() => {
    loadFileHistory();
  }, []);

  // 导入文件
  const handleImportFile = async () => {
    try {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.yaml,.yml,.txt';
      input.multiple = true;
      input.onchange = async (e) => {
        const files = Array.from((e.target as HTMLInputElement).files || []);
        let successCount = 0;
        
        for (const file of files) {
          try {
            const content = await file.text();
            loadFile(file.name, content);
            successCount++;
          } catch (error) {
            toast.error(`导入 ${file.name} 失败: ${error instanceof Error ? error.message : '未知错误'}`);
          }
        }
        
        if (successCount > 0) {
          toast.success(`成功导入 ${successCount} 个文件`);
          loadFileHistory();
        }
      };
      input.click();
    } catch (error) {
      toast.error('导入文件失败');
    }
  };

  // 导出历史
  const handleExportHistory = () => {
    try {
      const data = {
        exportTime: new Date().toISOString(),
        fileHistory: fileHistory
      };
      
      const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `yaml-editor-history-${new Date().toISOString().split('T')[0]}.json`;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      
      toast.success('历史记录已导出');
    } catch (error) {
      toast.error('导出失败');
    }
  };

  // 清空历史
  const handleClearHistory = () => {
    const confirmed = window.confirm('确定要清空所有文件历史吗？此操作不可撤销。');
    if (confirmed) {
      clearFileHistory();
      setFileHistory([]);
      toast.success('历史记录已清空');
    }
  };

  // 打开文件
  const handleOpenFile = (file: FileHistory) => {
    loadFile(file.filename, file.content);
    toast.success(`已打开文件: ${file.filename}`);
  };

  // 删除文件
  const handleDeleteFile = (fileId: string, filename: string) => {
    const confirmed = window.confirm(`确定要删除文件 "${filename}" 吗？`);
    if (confirmed) {
      deleteFileHistory(fileId);
      setFileHistory(prev => prev.filter(f => f.id !== fileId));
      toast.success(`已删除文件: ${filename}`);
    }
  };

  // 下载文件
  const handleDownloadFile = (file: FileHistory) => {
    try {
      const blob = new Blob([file.content], { type: 'text/yaml;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = file.filename;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
      toast.success(`已下载文件: ${file.filename}`);
    } catch (error) {
      toast.error('下载失败');
    }
  };

  // 过滤和排序文件
  const filteredAndSortedFiles = fileHistory
    .filter(file => 
      file.filename.toLowerCase().includes(searchTerm.toLowerCase())
    )
    .sort((a, b) => {
      let comparison = 0;
      
      switch (sortBy) {
        case 'name':
          comparison = a.filename.localeCompare(b.filename);
          break;
        case 'size':
          comparison = a.size - b.size;
          break;
        case 'lastModified':
          comparison = new Date(a.timestamp).getTime() - new Date(b.timestamp).getTime();
          break;
      }
      
      return sortOrder === 'asc' ? comparison : -comparison;
    });

  return (
    <div className="p-6 h-full flex flex-col">
      <div className="flex-shrink-0">
        <h1 className="text-2xl font-bold mb-6 flex items-center">
          <FolderOpen className="w-6 h-6 mr-2" />
          文件管理
        </h1>
        
        {/* 操作按钮 */}
        <div className="mb-6 flex flex-wrap gap-4">
          <button 
            onClick={handleImportFile}
            className="flex items-center px-4 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors"
          >
            <Upload className="w-4 h-4 mr-2" />
            导入文件
          </button>
          <button 
            onClick={handleExportHistory}
            className="flex items-center px-4 py-2 bg-green-600 text-white rounded hover:bg-green-700 transition-colors"
            disabled={fileHistory.length === 0}
          >
            <Download className="w-4 h-4 mr-2" />
            导出历史
          </button>
          <button 
            onClick={handleClearHistory}
            className="flex items-center px-4 py-2 bg-red-600 text-white rounded hover:bg-red-700 transition-colors"
            disabled={fileHistory.length === 0}
          >
            <Trash2 className="w-4 h-4 mr-2" />
            清空历史
          </button>
          <button 
            onClick={loadFileHistory}
            className="flex items-center px-4 py-2 bg-gray-600 text-white rounded hover:bg-gray-700 transition-colors"
          >
            <RefreshCw className="w-4 h-4 mr-2" />
            刷新
          </button>
        </div>
        
        {/* 搜索和排序 */}
        <div className="mb-6 flex flex-wrap gap-4 items-center">
          <div className="flex items-center space-x-2">
            <Search className="w-4 h-4 text-gray-500" />
            <input
              type="text"
              placeholder="搜索文件名..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              className="px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          
          <div className="flex items-center space-x-2">
            <Filter className="w-4 h-4 text-gray-500" />
            <select
              value={sortBy}
              onChange={(e) => setSortBy(e.target.value as 'name' | 'size' | 'lastModified')}
              className="px-3 py-2 border border-gray-300 rounded focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="lastModified">按修改时间</option>
              <option value="name">按文件名</option>
              <option value="size">按文件大小</option>
            </select>
            
            <button
              onClick={() => setSortOrder(prev => prev === 'asc' ? 'desc' : 'asc')}
              className="px-3 py-2 border border-gray-300 rounded hover:bg-gray-50 transition-colors"
            >
              {sortOrder === 'asc' ? '↑' : '↓'}
            </button>
          </div>
          
          <div className="text-sm text-gray-500">
            共 {filteredAndSortedFiles.length} 个文件
          </div>
        </div>
      </div>
      
      {/* 文件列表 */}
      <div className="flex-1 overflow-hidden">
        {filteredAndSortedFiles.length > 0 ? (
          <div className="bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden h-full flex flex-col">
            <div className="overflow-auto flex-1">
              <table className="min-w-full">
                <thead className="bg-gray-50 dark:bg-gray-700 sticky top-0">
                  <tr>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      <FileText className="w-4 h-4 inline mr-1" />
                      文件名
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      <HardDrive className="w-4 h-4 inline mr-1" />
                      大小
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      <Calendar className="w-4 h-4 inline mr-1" />
                      修改时间
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider">
                      操作
                    </th>
                  </tr>
                </thead>
                <tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
                  {filteredAndSortedFiles.map((file) => (
                    <tr key={file.id} className="hover:bg-gray-50 dark:hover:bg-gray-700">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="flex items-center">
                          <FileText className="w-4 h-4 text-blue-500 mr-2" />
                          <span className="text-sm font-medium text-gray-900 dark:text-gray-100">
                            {file.filename}
                          </span>
                        </div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                        {formatFileSize(file.size)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-gray-400">
                        {formatTime(file.timestamp)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm font-medium space-x-2">
                        <button 
                          onClick={() => handleOpenFile(file)}
                          className="text-blue-600 hover:text-blue-900 dark:text-blue-400 dark:hover:text-blue-300"
                        >
                          打开
                        </button>
                        <button 
                          onClick={() => handleDownloadFile(file)}
                          className="text-green-600 hover:text-green-900 dark:text-green-400 dark:hover:text-green-300"
                        >
                          下载
                        </button>
                        <button 
                          onClick={() => handleDeleteFile(file.id, file.filename)}
                          className="text-red-600 hover:text-red-900 dark:text-red-400 dark:hover:text-red-300"
                        >
                          删除
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        ) : (
          <div className="text-center py-12">
            <FolderOpen className="w-16 h-16 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-medium text-gray-900 dark:text-gray-100 mb-2">
              {searchTerm ? '未找到匹配的文件' : '暂无文件历史'}
            </h3>
            <p className="text-gray-500 dark:text-gray-400">
              {searchTerm ? '尝试修改搜索条件' : '开始编辑YAML文件，历史记录将显示在这里'}
            </p>
          </div>
        )}
      </div>
    </div>
  );
};

export default Files;